<?php
/**
 * Created by PhpStorm.
 * User: xiaoxin
 * Date: 2018/11/19 0019
 * Time: 9:32
 */

namespace app\admin\controller;
use think\Controller;
use app\admin\model\Cate as CateModel;
use think\Db;

class Cate extends Controller
{
	/**
	 * 分类页面主页
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
	public function index(){
		if (input('cate_name') && input('orderby')){
			if (!is_numeric(input('orderby'))){
				$this->error('请填写数字');
			}
			$is_set = CateModel::get(['orderby'=>input('orderby')]);
			if ($is_set){
				$this->error("该排序ID已存在");
			}
			$res = CateModel::create(['cate_name'=>input('cate_name'),'orderby'=>input('orderby')]);
			if ($res){
				echo '<script > location.href("{:url("admin/Cate/index")}");</script>';
			}else{
				$this->error("添加失败");
			}
		}
		$where = array ();
		input('order')=='desc' && $where['orderby']='desc';
		input('cate_id')=='desc' && $where['cate_id']='desc';
		input('order')=='' && $where['orderby']='';
		input('cate_id')=='' && $where['cate_id']='';
		$cate = Db::name('cate')->where('delete_time',null)->order($where)->paginate(10);
		$this->assign('cate',$cate);
	    return $this->fetch();
	}

	/*
	 * 删除分类
	 */
	public function del(){
		$cate_id = input('cate_id');
		$ok = CateModel::destroy($cate_id);
		if ($ok){
			$this->success('已删除');
		}else{
			$this->error('删除失败，请稍后在试');
		}
	}

	/**
	 * 修改分类
	 */
	public function edit(){
		$cate = CateModel::get(input('cate_id'));
		$this->assign('cate',$cate);
		return $this->fetch();
	}


	public function editCate(){
		$post = input('post.');
		if (!is_numeric($post['orderby'])){
			$this->error('请输入数字');
		}
		if (strlen($post['cate_name'])>18){
			$this->error('长度有点长');
		}
		$is_set = CateModel::where('cate_id','<>',$post['cate_id'])->where(['orderby'=>$post['orderby']])->select();
		if ($is_set){
			$this->error("该排序ID已存在");
		}
		$is_set_name = CateModel::get(['cate_name'=>$post['cate_name']]);
		if ($is_set_name){
			$this->error("该排序ID已存在");
		}
		$ok = CateModel::where('cate_id',$post['cate_id'])->update($post);
		if ($ok){
			$this->success('更改成功');
		}else{
			$this->error('更改失败，请稍后重试');
		}
	}
}